package com.huawei.cloud.phone.management.application.connection.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huawei.cloud.phone.management.domain.connection.Connection;
import com.huawei.cloud.phone.management.domain.connection.ConnectionParam;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Data
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConnectionDTO {
    /**
     * 用户的手机ID
     */
    @NotNull(message = "phone_id不能为空，且长度必须是32位")
    @Length(min = 32, max = 32, message = "phone_id不能为空，且长度必须是32位")
    @JsonProperty("phone_id")
    private String userPhoneId;

    /**
     * 客户端类型
     */
    @NotNull(message = "client_type不能为空")
    @Pattern(regexp = "ANDROID|HTML5", message = "client_type只能是ANDROID或者HTML5")
    @JsonProperty("client_type")
    private String clientType;

    /**
     * 手机接入ip
     */
    private String ip;

    /**
     * 手机接入端口号
     */
    private Integer port;

    /**
     * 连接建立后的会话ID
     */
    @JsonProperty("session_id")
    private String sessionId;

    /**
     * 应用放置后台的超时时间
     */
    @JsonProperty("background_timeout")
    private Integer backgroundTimeout;

    /**
     * 试玩时间
     */
    @JsonProperty("available_playtime")
    private Integer availablePlayTime;

    /**
     * 未触屏的超时花间
     */
    @JsonProperty("touch_timeout")
    private Integer touchTimeout;

    /**
     * 构造方法
     *
     * @param clientType 登录的客户端类型
     * @param loginInfo  登录数据
     * @param connection 连接数据
     */
    public ConnectionDTO(ConnectionDTO.ClientType clientType, ConnectionParam loginInfo, Connection connection) {
        this.copyLoginInfo(loginInfo);
        this.setConnectionInfo(clientType, connection);
    }

    private void copyLoginInfo(ConnectionParam loginInfo) {
        this.backgroundTimeout = loginInfo.getBackgroundTimeout();
        this.availablePlayTime = loginInfo.getAvailablePlayTime();
        this.touchTimeout = loginInfo.getTouchTimeout();
    }

    private void setConnectionInfo(ConnectionDTO.ClientType clientType, Connection connection) {
        this.setUserPhoneId(connection.getUserPhoneId());
        this.setSessionId(connection.getSessionId());
        this.setIp(connection.getPhone().getAccessIp());
        this.setPort(clientType == ConnectionDTO.ClientType.ANDROID ? connection.getPhone().getAccessAppPort() : connection.getPhone().getAccessH5Port());
    }

    public enum ClientType {
        ANDROID,
        HTML5;

        public static ClientType getClientType(String type) {
            return ClientType.valueOf(type);
        }
    }
}
